//
//  UIView+Extension.swift
//  Poetry
//
//  Created by cheyongzi on 2023/12/15.
//

import UIKit

extension UIView{
    @IBInspectable var radius: CGFloat {
        set{
            self.layer.cornerRadius = newValue
        }
        get{
            /// 这里返回的值其实是空的
            return self.radius
        }
    }
    @IBInspectable var borderWidth: CGFloat{
        set{
            self.layer.borderWidth = newValue
        }
        get {
            return self.borderWidth
        }
    }
    
    @IBInspectable var borderColor: UIColor?{
        set{
            guard let borderColor = newValue else {return}
            self.layer.borderColor = borderColor.cgColor
        }
        get{
            return self.borderColor
        }
    }
}

extension UIView {
    func gradientColor(_ startPoint: CGPoint, _ endPoint: CGPoint, _ colors: [CGColor], optionSize:CGSize? = .zero,location:[NSNumber]? = nil) {
        guard startPoint.x >= 0, startPoint.x <= 1, startPoint.y >= 0, startPoint.y <= 1, endPoint.x >= 0, endPoint.x <= 1, endPoint.y >= 0, endPoint.y <= 1 else {
            return
        }
        layoutIfNeeded()
        var gradientLayer: CAGradientLayer!
        gradientLayer = CAGradientLayer()
        if let size = optionSize, size.width > 0 {
            gradientLayer.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        }else {
            gradientLayer.frame = self.layer.bounds
        }
        gradientLayer.startPoint = startPoint
        gradientLayer.endPoint = endPoint
        gradientLayer.colors = colors
        gradientLayer.locations = location ?? [0,1]
        gradientLayer.cornerRadius = self.layer.cornerRadius
        gradientLayer.masksToBounds = true
        self.layer.insertSublayer(gradientLayer, at: 0)
        self.backgroundColor = UIColor.clear
        self.layer.masksToBounds = false
    }
    
    func convertToImage() -> UIImage? {
        let renderer = UIGraphicsImageRenderer(bounds: bounds)
        return renderer.image { rendererContext in
            layer.render(in: rendererContext.cgContext)
        }
    }
    
    var viewController: UIViewController? {
        var next: UIResponder? = self.next
        while next != nil {
            if let vc = next as? UIViewController {
                return vc
            }
            next = next?.next
        }
        return nil
    }
}
